import { defineEventHandler, getCookie, readBody, createError } from 'h3';
import scheduler from '../../utils/scheduler.js';

export default defineEventHandler(async (event) => {
  try {
    const userId = getCookie(event, 'userId');
    if (!userId) {
      throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
    }

    const { cronExpression, options = {} } = await readBody(event);
    
    if (!cronExpression) {
      throw createError({ statusCode: 400, statusMessage: 'Cron expression is required' });
    }

    // 验证 cron 表达式
    if (!scheduler.validateCronExpression(cronExpression)) {
      throw createError({ statusCode: 400, statusMessage: 'Invalid cron expression' });
    }

    // 启动定时备份任务
    const result = scheduler.startScheduledBackup(cronExpression, {
      name: `user_${userId}_${Date.now()}`,
      ...options
    });

    return {
      success: true,
      message: '定时备份任务已启动',
      task: result
    };
  } catch (error) {
    console.error('启动定时备份失败:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to schedule backup' });
  }
});
